<template>
  <!-- 文件操作 -->
  <div class="container">
    <div class="nav">
      <el-card class="nav-card">
        <el-button @click="dialogVisible = true">上传图片</el-button>
        <el-button @click="BatchDelete(tableChecked)">批量删除</el-button>
      </el-card>
    </div>
    <div class="content">
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <!-- <el-table-column label="Date" width="120">
      <template #default="scope">{{ scope.row.date }}</template>
    </el-table-column> -->
        <el-table-column prop="originalName" label="文件名" width="280">
          <template #default="scope">
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
              v-show="scope.$index === editIndex"
            >
              <el-input v-model="scope.row.originalName" />
              <div style="display: flex; align-items: center">
                <el-button
                  size="small"
                  @click="changeName(scope.row.id, scope.row.originalName)"
                  >确定</el-button
                >
                <el-button size="small" @click="back">取消</el-button>
              </div>
            </div>
            <span v-show="scope.$index !== editIndex">{{
              scope.row.originalName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="uploadTime" label="上传时间" width="220" />
        <el-table-column prop="url" label="图片预览" width="180">
          <template #default="scope">
            <div style="width: 60px; height: 60px">
              <img
                :src="scope.row.url"
                alt=""
                style="width: 60px; height: 60px"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column align="right">
          <template #header>
            <el-input
              v-model="search"
              size="small"
              placeholder="根据文件名搜索"
              style="height: 30px"
              clearable
            />
          </template>
          <template #default="scope">
            <div
              style="
                display: flex;
                justify-content: center;
                align-items: center;
              "
            >
              <el-button @click="handleEdit(scope.row)"> 编辑 </el-button>
              <el-button type="danger" @click="handleDelete(scope.row.id)">
                删除
              </el-button>
              <el-button type="primary" @click="handleDownload(scope.row.id)">
                下载
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin: 10px 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="limit"
          :total="totalCount"
          :current-page="currentPage"
          @current-change="pageChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      title="图片上传"
      style="width: 400px; height: 400px; overflow: hidden"
      draggable
      center
      destroy-on-close
      :lock-scroll="false"
      @close="digClose"
      :lock-scrollbar="false"
    >
      <!-- <el-scrollbar> -->
      <div style="height: 520px; overflow-y: auto">
        <el-upload
          :headers="{ Authorization: token }"
          class="upload-demo"
          action="http://localhost:8080/api/file/upload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :data="{ userId: userId }"
          list-type="picture"
          :limit="3"
          accept=".jpg,.jpeg,.png,gif,JPG,JPEG,PNG,GIF"
          :on-change="handleChange"
          :beforeUpload="beforeUpload"
        >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/jpeg/png/gif文件，且不超过3M,每次只能上传三张图片
            </div>
          </template>
        </el-upload>
        <!-- </el-scrollbar> -->
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  deleteBatch,
  fileDownload,
  filePage,
  logicDelete,
  reName,
  searchByName,
} from "@/api/fileOperation";
import { ref, watch } from "vue";
//定义search变量
const search = ref("");
const isShow = ref(false);
const dialogVisible = ref(false);
const editIndex = ref(-1);

//userId
const userId = JSON.parse(localStorage.getItem("user")).id;
const token = JSON.parse(localStorage.getItem("user")).token;
//当前页面
let currentPage = ref(1);
// 总条数
let totalCount = ref(0);
// 每页显示限制
let limit = ref(10);
const pageData = ref({
  pageNum: currentPage.value,
  pageSize: limit.value,
  userId: userId,
});
//获取数据
const tableData = ref([]);
const showPage = async () => {
  const res = await filePage(pageData.value);
  // console.log(res)
  // if (res.code == 200) {
  //   loading.value = false
  // }
  tableData.value = res.data.list;
  totalCount.value = res.data.total;
};
showPage();
// console.log(tableData.value)

//下载
const handleDownload = async (id) => {
  const res = await fileDownload(id);
  if (res.code == 200) {
    const url = res.data;
    // window.open(url)
    console.log(url);
    window.location.href = url + "?Authorization=" + token;
    ElMessage({
      showClose: true,
      message: "下载成功",
      type: "success",
    });
  } else {
    ElMessage({
      showClose: true,
      message: "下载失败",
      type: "error",
    });
  }
};
//编辑
const handleEdit = (row) => {
  editIndex.value = tableData.value.indexOf(row);
  console;
};
const renameData = ref({
  id: "",
  name: "",
});
const changeName = async (id, name) => {
  console.log(id, name);
  renameData.value.id = id;
  renameData.value.name = name;
  console.log(renameData.value);
  const res = await reName(renameData.value);
  // console.log(res)
  // isShow.value = false
  if (res.code == 200) {
    ElMessage({
      showClose: true,
      message: "修改成功",
      type: "success",
    });
  } else {
    ElMessage({
      showClose: true,
      message: "修改失败",
      type: "error",
    });
  }
  editIndex.value = -1;
  showPage();
};
const back = () => {
  // isShow.value = false
  editIndex.value = -1;
};
//删除
const handleDelete = (id) => {
  ElMessageBox.confirm("确定要删除吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    lockScroll: false, // 防止抖动
  })
    .then(async () => {
      const res = await logicDelete(id);
      //  console.log("data数据"+res.data)
      if (res.code == 200) {
        ElMessage({
          showClose: true,
          message: "删除成功",
          type: "success",
        });
        // showList()
        showPage();
      } else {
        ElMessage({
          showClose: true,
          message: res.data.msg,
          type: "error",
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
  showPage();
};
//关闭弹框
const digClose = () => {
  dialogVisible.value = false;
  showPage();
};
//分页
const pageChange = async (p) => {
  currentPage.value = p;
  pageData.value.pageNum = p;
  showPage();
};
//搜索功能
watch(search, async () => {
  searchData.value.fileName = search.value;
  const res = await searchByName(searchData.value);
  tableData.value = res.data.list;
  totalCount.value = res.data.total;
});
const searchData = ref({
  fileName: search.value,
  pageNum: currentPage.value,
  pageSize: limit.value,
  userId: userId,
});
//上传成功
const handleSuccess = (res, file) => {
  console.log(res, file);
  ElMessage({
    showClose: true,
    message: "上传成功",
    type: "success",
  });
  // }
};
const handlePreview = (file) => {
  console.log(file);
};
const handleRemove = (file, fileList) => {
  console.log(file, fileList);
  // ElMessage({
  //   showClose: true,
  //   message: '删除成功',
  //   type: 'success',
  // })
};
const handleChange = (file, fileList) => {
  console.log(file, fileList);
};
const beforeUpload = (file) => {
  //限制文件大小
  const maxSize = 3 * 1024 * 1024; //限制3M
  if (file.size > maxSize) {
    ElMessage.warning("文件大小不得超过3M");
    return false;
  }
  //限制文件格式
  const accept = ".jpg,.jpeg,.png,gif,JPG,JPEG,PNG,GIF";
  const isAccept = accept.split(",").some((item) => file.name.endsWith(item));
  if (!isAccept) {
    ElMessage.warning("文件格式不正确");
    return false;
  }
};
const tableChecked = ref([]);
const handleSelectionChange = (val) => {
  // console.log(val)
  tableChecked.value = val;
};
// const ids = ref([])
const BatchDelete = async (tableChecked) => {
  // console.log("批量删除");
  const arr = new Array();
  tableChecked.forEach((item) => {
    arr.push(item.id);
  });
  // console.log(ids);
  const ids = arr.join(",");
  // 调用删除函数并处理返回值

  if (tableChecked.length == 0) {
    ElMessage.warning("当前未勾选文件");
  } else {
    ElMessageBox.confirm("确定要删除吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      lockScroll: false, // 防止抖动
    })
      .then(async () => {
        const res = await deleteBatch(ids);
        //  console.log("data数据"+res.data)
        if (res.code == 200) {
          ElMessage({
            showClose: true,
            message: "删除成功",
            type: "success",
          });
          // showList()
          showPage();
        } else {
          ElMessage({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
        }
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除",
        });
      });
  }
};
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  /* background-color: violet; */
  /* overflow: hidden; */
}
.nav {
  height: 60px;
  margin-top: 10px;
}
.nav-card {
  height: 100%;
  display: flex;
  /* justify-content: center; */
  align-items: center;
}
.content {
  margin-top: 10px;
  /* overflow: hidden; */
}
/* .el-dialog span.el-dialog_title {
  text-align: center;
} */
</style>